package com.zhulin.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhulin.reggie.common.CustomException;
import com.zhulin.reggie.dto.SetmealDto;
import com.zhulin.reggie.entity.Setmeal;
import com.zhulin.reggie.entity.SetmealDish;
import com.zhulin.reggie.mapper.SetmealMapper;
import com.zhulin.reggie.service.SetmealDishService;
import com.zhulin.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐同时保留套餐和菜品关系
     *
     * @param setmealDto
     */
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        //保存菜品和套餐的关联信息
        setmealDishService.saveBatch(setmealDishes);

    }

    /**
     * 删除套餐同时删除套餐和菜品关系
     *
     * @param id
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> id) {
        //查询状态确定是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, id);
        queryWrapper.eq(Setmeal::getStatus, 1);
        int count = this.count(queryWrapper);
        if (count > 0) {
            //不能删除，拋业务异常
            throw new CustomException("套餐正在售卖中，不能删除");
        }

        //如果可删除，先删除套餐表中数据
        this.removeById((Serializable) id);
        //删除关系表中的数据
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,id);

        setmealDishService.remove(lambdaQueryWrapper);
    }
}
